<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/3/3
 * Time: 10:02
 */
class SettlementAction extends Action{
    //供应商结算列表
    public function vendorSettlementList($name='',$status=null,$tixianNumber='',$start=0,$limit=10,$isExport=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        $id=session("id");
        $vid = self::getVidById($id);
        Session::switchCustomer(0);
        $vendorTixian = M('vendor_tixian');
        Session::switchCustomer($cid);
        isset($status)&&$status!=null?$condition['a.state']=array('eq',$status):"";
        empty($tixianNumber)? :$condition['a.tixianNumber']=array('like','%'.$tixianNumber.'%');
        empty($name)? :$condition['b.name']=array('like','%'.$name.'%');
        $condition['b.cId']=array('eq',$cid);
        if($vid){
            $condition['a.vId']=array('eq',$vid);
        }
        if(!$isExport){
            $result = $vendorTixian->alias('a')
                ->join("inner join wx_mivendor b on a.vId=b.id")
               // ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                ->field("a.*,b.name")
                ->order("a.createTime desc")
                ->where($condition)
                ->limit($start,$limit)
                ->select();
            if($result){
                foreach ($result as $key=>$value){
                    $result[$key]['cash'] = round($value['cash'],2);
                }
                $count = $vendorTixian->alias('a')
                    ->join("inner join wx_mivendor b on a.vId=b.id")
                    ->where($condition)
                    ->count();
                Output::instance()->objArray($result,$count);
            }else{
                Output::instance()->resultCode();
            }
        }else{
            if($vid){
                $arr = $vendorTixian->alias('a')
                    ->join("inner join wx_mivendor b on a.vId=b.id")
                    //->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                    ->field("a.cash,a.state,a.tixianNumber,a.createTime")
                    ->order("a.createTime desc")
                    ->where($condition)
                    ->select();
                $data[0] = array(
                    'cash'=>'结算金额',
                    'state' => '结算状态',
                    'tixianNumber'=>'结算单号',
                    'createTime' => '申请时间',
                    'isNum'=>'0',
                    'istitle'=>'1'
                );
            }else{
                $arr = $vendorTixian->alias('a')
                    ->join("inner join wx_mivendor b on a.vId=b.id")
                    //->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                    ->field("b.name,a.cash,a.state,a.tixianNumber,a.createTime")
                    ->order("a.createTime desc")
                    ->where($condition)
                    ->select();
                $data[0] = array(
                    'name'=>'供应商名称',
                    'cash'=>'结算金额',
                    'state' => '结算状态',
                    'tixianNumber'=>'结算单号',
                    'createTime' => '申请时间',
                    'isNum'=>'1',
                    'istitle'=>'1'
                );
            }
            foreach ($arr as $k1 => $v1) {
                if($v1['state']){
                    $v1['state']='已结算';
                }else{
                    $v1['state']='未结算';
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('供应商结算'.date("Y-m-d H:i:s"), '', $data);

        }
    }
    //供应商结算
    public function vendorSettlementByIds($ids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $customer_user_model = M('customer_user');
        $vendorTixian = M('vendor_tixian');
        Session::switchCustomer($cid);
        $TemplateModel = M("template_messages");
        $vendorTixian->startTrans();
        $condition['id']=array('in',$ids);
        $data['state']=1;
        $data['completeTime']=date('Y-m-d H:i:s');
        $result = $vendorTixian->where($condition)->save($data);
        $sql = $vendorTixian->getLastSql();
        //发送站内消息
        $arrs = $vendorTixian->where($condition)->select();
        foreach ($arrs as $arr) {
            $receiveIds = $customer_user_model->where(['customerId' => $cid, 'vid' => $arr['vId']])->getField('id', true);
            if ($receiveIds) {
                $message = '<p>您的结算单号为' . $arr['tixianNumber'] . '的结算申请已经结算完毕，请前往结算中心查看，<a href = "#/joymap/incomeAndSettlement/settlement">前往查看</a></p>';
                PlatMessageAction::pushMessage('结算完毕提醒', $message, $receiveIds, '', 0, 'newAllocation', '结算', 2, 1, 0, 0, $message, $cid);
            }
        }
        //发送模板消息
        $settlementList = $vendorTixian->alias("a")
            ->join("inner join wx_mivendor b on a.vId=b.id")
            ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
            ->where("a.id in ($ids)")
            ->field('a.cash,a.tixianNumber,a.completeTime,c.openid, a.vId')
            ->select();
        foreach($settlementList as $key=>$value){
            $toUser = $value['openid'];
//            $receiveIds = [];
//            $receiveIds[] = $value['customerUserId'];
            if($toUser){
                $twhere['status'] = "settlementSuccess";
                $templatemsg = $TemplateModel->where($twhere)->find();
                $templateId = $templatemsg['templateId'];
                $data['first'] = array('value'=> '亲，您有一笔收益到账，请注意查收！','color'=>"#743A3A");
                $data['keyword1'] = array('value'=> $value['cash'].'元','color'=>'#173177');
                $data['keyword2'] = array('value'=> date("Y-m-d H:i:s",time()),'color'=>'#173177');
                $data['keyword3'] = array('value'=> '您提交的结算申请已经通过，资金已经汇入您的指定账号。','color'=>'#173177');
                $data['remark'] = array('value'=> '请注意查收，如有疑问，请咨询400-867-9299。',"color"=>'#008000');
                $url = C("SERVER_HOST") . "call.html?customerId=" . $cid ."&module=settlement&method=index";
                $template_id = $templateId;
                $url = urlencode($url);
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
            }
        }
        if($result){
            $vendorTixian->commit();
            R('Log/add',array('newInSettlement','','结算',op_update,$sql,'确认商家结算'));
            Output::instance()->resultCode();
        }else{
            $vendorTixian->rollback();
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //代理商结算列表
    public function agentSettlementList($name='',$status=0,$tixianNumber='',$start=0,$limit=10,$isExport=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorTixian = M('agent_tixian');
        Session::switchCustomer($cid);
        isset($status)&&$status!=null?$condition['a.state']=array('eq',$status):"";
        $condition['a.tixianNumber']=array('like','%'.$tixianNumber.'%');
        $condition['b.name']=array('like','%'.$name.'%');
        $condition['c.customerId']=array('eq',$cid);
        if(!$isExport){
            $result = $vendorTixian->alias('a')
                ->join("inner join wx_vendor_agent b on a.agentId=b.id")
               ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                ->field("a.*,b.name")
                ->where($condition)
                ->order("a.createTime desc")
                ->limit($start,$limit)
                ->select();
            if($result){
                $count = $vendorTixian->alias('a')
                    ->join("inner join wx_vendor_agent b on a.agentId=b.id")
                    ->where($condition)
                    ->count();
                Output::instance()->objArray($result,$count);
            }else{
                Output::instance()->resultCode();
            }
        }else{
            $arr = $vendorTixian->alias('a')
                ->join("inner join wx_vendor_agent b on a.agentId=b.id")
                ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
                ->field("b.name,a.cash,a.state,a.tixianNumber,a.createTime")
                ->order("a.createTime desc")
                ->select();
            $data[0] = array(
                'name'=>'代理商名称',
                'cash'=>'结算金额',
                'state' => '结算状态',
                'tixianNumber'=>'结算单号',
                'createTime' => '申请时间',
                'isNum'=>'1,3',
                'istitle'=>'1'
            );
            foreach ($arr as $k1 => $v1) {
                if($v1['state']){
                    $v1['state']='已结算';
                }else{
                    $v1['state']='未结算';
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('代理商结算'.date("Y-m-d H:i:s"), '', $data);
        }
    }

    //代理商结算
    public function agentSettlementByIds($ids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorTixian = M('agent_tixian');
        Session::switchCustomer($cid);
        $TemplateModel = M("template_messages");
        $vendorTixian->startTrans();
        $data['state']=1;
        $data['completeTime']=date('Y-m-d H:i:s');
        $condition['id']=array('in',$ids);
        $result = $vendorTixian->where($condition)->save($data);
        //发送模板消息
        $settlementList = $vendorTixian->alias("a")
            ->join("inner join wx_vendor_agent b on a.agentId=b.id")
            ->join("inner join wx_customer_user c on b.fromCustomerUserId=c.id")
            ->where("a.id in ($ids)")
            ->field('a.cash,a.tixianNumber,a.completeTime,c.openid')
            ->select();
        foreach($settlementList as $key=>$value){
            $toUser = $value['openid'];
            if($toUser){
                $twhere['status'] = "settlementSuccess";
                $templatemsg = $TemplateModel->where($twhere)->find();
                $templateId = $templatemsg['templateId'];
                $data['first'] = array('value'=> '亲，您有一笔收益到账，请注意查收！','color'=>"#743A3A");
                $data['keyword1'] = array('value'=> $value['cash'].'元','color'=>'#173177');
                $data['keyword2'] = array('value'=> date("Y-m-d H:i:s",time()),'color'=>'#173177');
                $data['keyword3'] = array('value'=> '您提交的结算申请已经通过，资金已经汇入您的指定账号。','color'=>'#173177');
                $data['remark'] = array('value'=> '请注意查收，如有疑问，请咨询400-867-9299。',"color"=>'#008000');
                $url = C("SERVER_HOST") . "call.html?customerId=" . $cid ."&module=settlement&method=index";
                $template_id = $templateId;
                $url = urlencode($url);
                $topcolor = "#FF0000";
                WeixinApi::sendTpl($toUser, $template_id, $url,$topcolor,$data);
            }
        }
        if($result){
            $vendorTixian->commit();
            Output::instance()->resultCode();
        }else{
            $vendorTixian->rollback();
            Output::instance()->resultCode(code_sql_error);
        }

    }

    /**
     * 供应商收入列表
     *
     * @param null   $vid
     * @param string $name
     * @param string $serialNumber
     * @param string $description
     * @param null   $type
     * @param null   $status
     * @param null   $startTime
     * @param null   $endTime
     * @param int    $start
     * @param int    $limit
     * @param string    $module  分类，仓库：depot，订单：order
     *
     * @modify lilei<LL_strive@163.com> 2017-04-24
     */
    public function vendorIncome($vid=null,$name='',$serialNumber='',$description='',$type=null,$status=null,$startTime=null,$endTime=null,$start=0,$limit=10,$isExport=0,$module=''){
        /** 1. 判断用户登录, 获得session相关数据 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        $id = session("id");

        /** 2. 实例化相关数据模型 */
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        $customerUser =M("customer_user");
        Session::switchCustomer($cid);

        /** 3. 组织筛选数据条件 */
        // 3.1 排序规则【孟慧更改于20180309，时间统一更改为a.createTime】
//        if ($vid) {
           $order = "a.createTime desc";
//        } else {
//            $vid = self::getVidById($id);
//            $order = "b.createTime desc";
//        }
        // 3.2 筛选条件
        $supplyRelation = $customerUser->where("id=$id")->getField("supplyRelation");
        if ($vid) {
            $where['a.vId'] = array("eq", $vid);
        }
        $where['c.cId']=array('eq',$cid);
        $where['a.deleted'] = array('eq', 0);
        $name ? $where['c.name'] = array("like", "%$name%") : "";
        //孟慧修改于20180307，用于收入分类筛选
        if($module) {
            if ($module=='depot') {
                $where['a.module'] = array("EQ", 'depot') ;
            }else {
                $where['a.module'] = array("neq", 'depot') ;
            }
        }

        $serialNumber ? $where['a.serialNumber'] = array("like", "%$serialNumber%") : "";
        $where['a.description'] = array("like", "%$description%");
        $type != null ? $where['a.type'] = array("eq", $type) : "";
        $status != null ? $where['a.status'] = array("eq", $status) : "";
        //孟慧修改于20180309，将时间筛选由原来的b.createTime改为a.createTime.
        if ($startTime && $endTime) {
            $where['a.createTime'] = array(array("gt", $startTime), array("lt", $endTime), "and");
        } else {
            $startTime ? $where['a.createTime'] = array("gt", $startTime) : "";
            $endTime ? $where['a.createTime'] = array("lt", $endTime) : "";
        }
        /** 4. 返回数据 */
        if (!$isExport) {   // 非导出Excel, 正常返回json串
            $arr = $accountVendor->alias("a")
                ->join("inner join wx_mivendor c on a.vId=c.id")
               // ->join("left join wx_module_product_order b on a.oId=b.id")
                ->field("a.id,a.description,a.module,a.moduleId,a.money,a.type,a.status,a.createTime,a.serialNumber,a.oId as oid,c.name,a.createTime as vendorTime")//修改createTime取处
                ->where($where)
                ->limit($start, $limit)
                ->order($order)
                ->select();
                Log::write("商家结算  ".$accountVendor->getLastSql());
            if ($arr) { // 如果有数据, 则对数据进一步处理(去掉limit筛选, 查询所有符合条件的记录总数)
                foreach ($arr as $key=>$value){
                    $arr[$key]['money'] = round($value['money'],2);
                }
                $count = $accountVendor->alias("a")
                    ->join("inner join wx_mivendor c on a.vId=c.id")
                    ->join("left join wx_module_product_order b on a.oId=b.id")
                    ->where($where)
                    ->count();
                Output::instance()->objArray($arr, $count);
            } else {    // 如果没有数据, 则直接返回
                Output::instance()->resultCode();
            }
        } else {
            if ($vid) {
                unset($where['d.customerId']);
                unset($where['c.cId']);
                $arr = $accountVendor->alias("a")
                    //->join("inner join wx_module_product_order b on a.oId=b.id")
                    //->join("inner join wx_module_product_order_detail c on a.moduleId=c.id and a.module='orderDetail'")
                   // ->field("b.serialNumber,a.createTime,a.description,c.serialNumber as proSerialNumber,a.money,c.count,c.isVendorCut,a.type,a.status")
                    ->field("a.serialNumber,a.createTime,a.description,a.money,a.type,a.status")
                    ->where($where)
                    ->order("a.createTime desc")
                    ->select();
                foreach ($arr as $key=>$value){
                    $arr[$key]['money'] = round($value['money'],2);
                }
                if ($supplyRelation != 2) {
                    $data[0] = array(
                        'serialNumber' => '订单号',
                        'createTime' => '时间',
                        'description' => '详情',
                        'proSerialNumber' => '商品条码',
                        'money' => '金额',
                        'count' => "数量",
                        'isVendorCut' => '供货价',
                        'type' => '收支状态',
                        'status' => "状态",
                        'isNum' => '4,5,6',
                        'istitle' => '1'
                    );
                } else {
                    $data[0] = array(
                        'serialNumber' => '订单号',
                        'createTime' => '时间',
                        'description' => '详情',
                        'proSerialNumber' => '商品条码',
                        'money' => '金额',
                        'count' => "数量",
                        'type' => '收支状态',
                        'status' => "状态",
                        'isNum' => '4,5',
                        'istitle' => '1'
                    );
                }

            } else {
                $arr = $accountVendor->alias("a")
                    ->join("inner join wx_mivendor c on a.vId=c.id")
                    //->join("wx_module_product_order b on a.oId=b.id")
                    //->join("inner join wx_module_product_order_detail e on a.moduleId=e.id and a.module='orderDetail'")
                    //->field("c.name,b.serialNumber,a.createTime,a.description,e.serialNumber as proSerialNumber,a.money,e.count,e.isVendorCut,a.type,a.status")
                    ->field("c.name,a.serialNumber,a.createTime,a.description,a.money,a.type,a.status")
                    ->where($where)
                    ->order("a.createTime desc")
                    ->select();
                if ($supplyRelation != 2) {
                    $data[0] = array(
                        'name' => "供应商名称",
                        'serialNumber' => '订单号',
                        'createTime' => '时间',
                        'description' => '详情',
                        'proSerialNumber' => '商品条码',
                        'money' => '金额',
                        'count' => "数量",
                        'isVendorCut' => '供货价',
                        'type' => '收支状态',
                        'status' => "状态",
                        'isNum' => '5,6,7',
                        'istitle' => '1'
                    );
                } else {
                    $data[0] = array(
                        'name' => "供应商名称",
                        'serialNumber' => '订单号',
                        'createTime' => '时间',
                        'description' => '详情',
                        'proSerialNumber' => '商品条码',
                        'money' => '金额',
                        'count' => "数量",
                        'type' => '收支状态',
                        'status' => "状态",
                        'isNum' => '5,6',
                        'istitle' => '1'
                    );
                }

            }
            foreach ($arr as $k1 => $v1) {
                if ($v1['type']) {
                    $v1['type'] = '支出';
                } else {
                    $v1['type'] = '收入';
                }
                if ($v1['status']) {
                    $v1['status'] = '未确认';
                } else {
                    $v1['status'] = '已确认';
                }
                if ($supplyRelation == 2) {
                    unset($v1['isVendorCut']);
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('供应商收入' . date("Y-m-d H:i:s"), '', $data);

        }

    }
    //供应商基本信息
    public function vendorBasicInfo(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendor = M("mivendor");
        Session::switchCustomer($cid);
        $id = session("id");
        $vid=self::getVidById($id);
        $result = $vendor->where("id=$vid")->find();
        Output::instance()->object($result);
    }
    //供应商提现
    public function vendorTixian($money){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        $id = session("id");
        $vid=self::getVidById($id);
        $param = new stdClass();
        $param->id=$vid;
        $param->cash=$money;
        $param->agent="vendor";
        $param->cuid=$id;
        R('Log/add',array('newInSettlement','','结算',op_add,'','新建结算申请'));
        Module::callModule("settlement",NULL,"saveCash",$param);

    }
    //添加收入
    public function saveNewIncome($money,$description,$type){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        Session::switchCustomer($cid);
        $id = session("id");
        $vid=self::getVidById($id);
        $data=array(
            "vId"=>$vid,
            "money"=>$money,
            "description"=>$description,
            "type"=>$type,
            "status"=>1,
            "deleted"=>0,
            "createTime"=>date("Y-m-d H:i:s")
        );
        $result = $accountVendor->add($data);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //确认收入
    public function beSureIncome($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        Session::switchCustomer($cid);
        $result = $accountVendor->where("id=$id")->setField("status",0);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //当前账号供应商ID
    private static function getVidById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser =M("customer_user");
        Session::switchCustomer($cid);
        //孟慧修改获取供应商的id的方式20180307
        // $vendorInfo = $customerUser->alias("a")
        //     ->join("inner join wx_mivendor b on a.id=b.fromCustomerUserId")
        //     ->where("a.id=$id")
        //     ->field("b.id")
        //     ->find();
        $vendorInfo = $customerUser->field('vid')->where("id=$id")->find();
        return $vendorInfo['vid'];
    }
    //供应链收入
    public function supplyIncome($channelId=null,$serialNumber='',$description='',$type=null,$startTime=null,$endTime=null,$start=0,$limit=10,$isExport=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountSupply =M("account_supply_chain");
        $customerUser = M("customer_user");
        Session::switchCustomer($cid);
        $id = session("id");
        $customerUserInfo = $customerUser->where("id=$id")->find();
        if($customerUserInfo['supplyRelation']==1){
            $where['a.supplyChainId']=array("eq",$customerUserInfo['supplyChainId']);
        }else if($customerUserInfo['supplyRelation']==2) {
            $where['a.supplyChainId']=array("eq",$customerUserInfo['supplyChainId']);
            $where['a.channelId']=array("eq",$id);
        }else {
            Output::instance()->resultCode();
            return;
        }
        $where['a.deleted']=array('eq',0);
        $channelId?$where['a.channelId']=array("eq","$channelId"):"";
        $serialNumber?$where['b.serialNumber']=array("like","%$serialNumber%"):"";
        $where['a.description']=array("like","%$description%");
        $type!=null?$where['a.type']=array("eq",$type):"";
        if($startTime&&$endTime){
            $where['b.createTime']=array(array("gt",$startTime),array("lt",$endTime),"and");
        }else{
            $startTime?$where['b.createTime']=array("gt",$startTime):"";
            $endTime?$where['b.createTime']=array("lt",$endTime):"";
        }
        if(!$isExport){
            $arr = $accountSupply->alias("a")
                ->join("inner join wx_module_product_order b on a.oId=b.id")
                ->join("inner join wx_customer_user c on a.channelId=c.id")
                ->field("a.id,a.description,a.money,a.type,b.createTime,b.serialNumber,b.id as oid,c.fullName as name")
                ->where($where)
                ->limit($start,$limit)
                ->order("b.createTime desc")
                ->select();
            if($arr){
                $count = $accountSupply->alias("a")
                    ->join("inner join wx_module_product_order b on a.oId=b.id")
                    ->where($where)
                    ->count();
                Output::instance()->objArray($arr,$count);
            }else{
                Output::instance()->resultCode();
            }
        }else{
            if($customerUserInfo['supplyRelation']==2){
                $arr = $accountSupply->alias("a")
                    ->join("inner join wx_module_product_order b on a.oId=b.id")
                    ->join("inner join wx_customer_user c on a.channelId=c.id")
                    ->field("b.serialNumber,a.createTime,a.description,a.money,a.type")
                    ->where($where)
                    ->order("b.createTime desc")
                    ->select();
                $data[0] = array(
                    'serialNumber'=>'订单号',
                    'createTime'=>'时间',
                    'description' => '详情',
                    'money'=>'金额',
                    'type' => '收支状态',
                    'isNum'=>'3',
                    'istitle'=>'1'
                );
            }else{
                $arr = $accountSupply->alias("a")
                    ->join("wx_module_product_order b on a.oId=b.id")
                    ->join("inner join wx_customer_user c on a.channelId=c.id")
                    ->field("c.fullName as name,b.serialNumber,a.createTime,a.description,a.money,a.type")
                    ->where($where)
                    ->order("b.createTime desc")
                    ->select();
                $data[0] = array(
                    'name'=>"渠道名称",
                    'serialNumber'=>'订单号',
                    'createTime'=>'时间',
                    'description' => '详情',
                    'money'=>'金额',
                    'type' => '收支状态',
                    'isNum'=>'4',
                    'istitle'=>'1'
                );
            }
            foreach ($arr as $k1 => $v1) {
                if($v1['type']){
                    $v1['type']='支出';
                }else{
                    $v1['type']='收入';
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('供应链收入'.date("Y-m-d H:i:s"), '', $data);

        }

    }
    //供应链结算列表
    public function supplySettlementList($channelId='',$status=null,$tixianNumber='',$start=0,$limit=10,$isExport=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        $id=session("id");
        Session::switchCustomer(0);
        $supplyTixian = M('supply_chain_tixian');
        $customerUser = M("customer_user");
        Session::switchCustomer($cid);
        $customerUserInfo = $customerUser->where("id=$id")->find();
        isset($status)&&$status!=null?$condition['a.state']=array('eq',$status):"";
        $condition['a.tixianNumber']=array('like','%'.$tixianNumber.'%');
        $condition['a.channelId']=array('eq',$channelId);
        if($customerUserInfo['supplyRelation']==1){
            $condition['a.supplyChainId']=array("eq",$customerUserInfo['supplyChainId']);
        }else if($customerUserInfo['supplyRelation']==2) {
            $condition['a.supplyChainId']=array("eq",$customerUserInfo['supplyChainId']);
            $condition['a.channelId']=array("eq",$id);
        }else {
            Output::instance()->resultCode();
            return;
        }
        if(!$isExport){
            $result = $supplyTixian->alias("a")
                ->join("inner join wx_customer_user b on a.channelId=b.id")
                ->field("a.id,a.cash,a.state,a.tixianNumber,a.description,a.createTime,a.completeTime,b.fullName as channelName")
                ->order("a.createTime desc")
                ->where($condition)
                ->limit($start,$limit)
                ->select();
            if($result){
                $count = $supplyTixian->alias("a")
                    ->join("inner join wx_customer_user b on a.channelId=b.id")
                    ->where($condition)
                    ->count();
                Output::instance()->objArray($result,$count);
            }else{
                Output::instance()->resultCode();
            }
        }else{
            if($customerUserInfo['supplyRelation']==2){
                $arr = $supplyTixian->alias("a")
                    ->join("inner join wx_customer_user b on a.channelId=b.id")
                    ->field("a.cash,a.state,a.tixianNumber,a.createTime")
                    ->order("a.createTime desc")
                    ->where($condition)
                    ->select();
                $data[0] = array(
                    'cash'=>'结算金额',
                    'state' => '结算状态',
                    'tixianNumber'=>'结算单号',
                    'createTime' => '申请时间',
                    'isNum'=>'0',
                    'istitle'=>'1'
                );
            }else{
                $arr = $supplyTixian->alias("a")
                    ->join("inner join wx_customer_user b on a.channelId=b.id")
                    ->field("b.fullName as name,a.cash,a.state,a.tixianNumber,a.createTime")
                    ->order("a.createTime desc")
                    ->where($condition)
                    ->select();
                $data[0] = array(
                    'name'=>'渠道名称',
                    'cash'=>'结算金额',
                    'state' => '结算状态',
                    'tixianNumber'=>'结算单号',
                    'createTime' => '申请时间',
                    'isNum'=>'1',
                    'istitle'=>'1'
                );
            }
            foreach ($arr as $k1 => $v1) {
                if($v1['state']){
                    $v1['state']='已结算';
                }else{
                    $v1['state']='未结算';
                }
                $data[] = $v1;
            }
            Output::instance()->objArrayExcel('供应链结算'.date("Y-m-d H:i:s"), '', $data);

        }
    }
    //供应链结算
    public function supplySettlementByIds($ids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyTixian = M('supply_chain_tixian');
        Session::switchCustomer($cid);
        $supplyTixian->startTrans();
        $condition['id']=array('in',$ids);
        $data['state']=1;
        $data['completeTime']=date('Y-m-d H:i:s');
        $result = $supplyTixian->where($condition)->save($data);
        if($result){
            $supplyTixian->commit();
            Output::instance()->resultCode();
        }else{
            $supplyTixian->rollback();
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //供应链余额
    public function supplyBalance($name='',$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        $id=session("id");
        Session::switchCustomer(0);
        $supplyModel = M('module_supply_chain');
        Session::switchCustomer($cid);
        $name?$where['b.channelName']=array("like","%$name%"):"";
        $where['a.customerUserId']=array("eq",$id);
        $where['a.deleted']=array("eq",0);
        $where['b.deleted']=array("eq",0);
        $where['a.cId']=array("eq",$cid);
        $arr = $supplyModel->alias("a")
            ->join("inner join wx_supply_chain_balance b on a.id=b.supplyChainId")
            ->join("inner join wx_customer_user c on b.channelId=c.id")
            ->where($where)
            ->order("b.balance desc")
            ->field("b.id,b.supplyChainId,c.fullName as channelName,b.balance,b.totalRevenue,b.totalTixian,b.channelId")
            ->limit("$start,$limit")
            ->select();
        if($arr){
            $count = $supplyModel->alias("a")
                ->join("inner join wx_supply_chain_balance b on a.id=b.supplyChainId")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    public function supplyTixian($id,$money){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyBalance = M('supply_chain_balance');
        $supplyTixian = M("supply_chain_tixian");
        Session::switchCustomer($cid);
        if(date("N")!=2){
            Output::instance()->resultCode(1,'每周二才可以申请结算！');
            return;
        }
        if(!preg_match('/^[0-9]{1,}\.?\d{1,}$|^\d$/',$money)){
            Output::instance()->resultCode(1,'请输入数字！');
            return;
        }
        if($money<100){
            Output::instance()->resultCode(1,'单笔结算金额必须大于100元！');
            return;
        }
        $balanceInfo = $supplyBalance->where("id=$id")->find();
        if($money>$balanceInfo['balance']){
            Output::instance()->resultCode(1,'余额不足！');
            return;
        }
        $millisecond = explode(' ', microtime());
        $tixianNumber = date('YmdHis').sprintf('%.0f',$millisecond[0]*1000).mt_rand(100,999);
        $data['supplyChainId']=$balanceInfo['supplyChainId'];
        $data['channelId']=$balanceInfo['channelId'];
        $data['channelName']=$balanceInfo['channelName'];
        $data['cash']=$money;
        $data['state']=0;
        $data['tixianNumber']=$tixianNumber;
        $data['createTime']=date('Y-m-d H:i:s');
        $supplyTixian->add($data);
        $balanceData['totalTixian']=$balanceInfo['totalTixian']+$money;
        $balanceData['balance']=$balanceInfo['balance']-$money;
        $balanceData['updateTime']=date('Y-m-d H:i:s');
        $supplyBalance->where("id=$id")->save($balanceData);
        Output::instance()->resultCode();
    }
    //商家流水详情
    public function vendorAccDetail($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid=Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorVisit = M("vendor_user_visit");
        Session::switchCustomer($cid);
        $arr = $vendorVisit->alias('a')
            ->join("wx_".$cid."_user_weixin_info b on a.userId=b.userId")
            ->where("a.id=$id")
            ->field("a.id,a.createTime,a.keywords,b.nickname,b.headimgurl")
            ->select();
        Output::instance()->objArray($arr,1);

    }

    /**
     * 商家收入统计
     * @param
     */
    public function vendorIncomeStatic()
    {
        /** 1. 判断用户登录, 获得session相关数据 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $id = session("id");

        /** 2. 实例化相关数据模型 */
        Session::switchCustomer(0);
        $mivendor = M("mivendor");
        Session::switchCustomer($cid);

        /** 3. 组织筛选数据条件 */
        $vid = self::getVidById($id);
        $where['cId'] = $cid;
        if ($vid){
            $where['id'] = array("EQ", $vid);
            $totalRevenue = $mivendor->where($where)->getField('totalRevenue');
            $totalRevenue = round($totalRevenue,2);
        }else{
            $totalRevenue = $mivendor->where($where)->getField('SUM(totalRevenue) as totalRevenue');
            $totalRevenue = round($totalRevenue,2);
        }
        $return['code'] = 0;
        $return['msg'] = '总收入信息';
        $return['data'] = $totalRevenue;
        Output::instance()->object($return);
    }

    /**
     * 商家余额统计
     * @param
     */
    public function vendorAccountStatic()
    {
        /** 1. 判断用户登录, 获得session相关数据 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $id = session("id");

        /** 2. 实例化相关数据模型 */
        Session::switchCustomer(0);
        $mivendor = M("mivendor");
        $tixian = M("vendor_tixian");
        Session::switchCustomer($cid);

        /** 3. 组织筛选数据条件 */
        $vid = self::getVidById($id);
        $where['cId'] = $cid;
        if ($vid){
            $where['id'] = array("EQ", $vid);
            $vendorInfo = $mivendor->field('totalTixian,balance')->where($where)->find();
        }else{
            $vendorInfo['balance'] = $mivendor->where($where)->getField('SUM(balance) as balance');
            $where_tixian['a.state'] = 1;
            $where_tixian['b.cId'] = $cid;
            $vendorInfo['totalTixian'] =  $tixian->alias('a')
                ->join("wx_mivendor b on a.vId=b.id")
                ->where($where_tixian)
                ->getField("SUM(cash) as totalTixian");

        }
        $vendorInfo['balance'] = round( $vendorInfo['balance'] ,2);
        $vendorInfo['totalTixian'] = round( $vendorInfo['totalTixian'] ,2);
        $return['code'] = 0;
        $return['msg'] = '金额信息';
        $return['data'] = $vendorInfo;
        Output::instance()->object($return);
    }
    //原订单中的数据迁移
    public function  dataMargain(){

        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        $order =M("module_product_order");

        $where['module'] = 'orderDetail';
        $accountInfo = $accountVendor->field('id,oId')->where($where)->select();
        foreach ($accountInfo as $key=>$value) {
            $serialNumber = $order->where("id=".$value['oId'])->getField('serialNumber');
            $accountVendor->where('id='.$value['id'])->setField('serialNumber',$serialNumber);
        }
    }


}